package com.rongxun.main.viewmodel;

import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.rongxun.api.config.Constants;
import com.rongxun.api.dao.response.Advertisement;
import com.rongxun.common.aroute.RouteUtil;
import com.rongxun.common.base.mvvm.viewmodel.BaseViewModel;
import com.rongxun.common.utils.StringUtil;
import com.rongxun.common.utils.UMengEventUtils;
import com.rongxun.main.R;
import com.rongxun.main.model.AdvertisementModel;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.databinding.ObservableField;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 创建者     forza
 * 创建时间   2019/11/29 18:09
 * 描述
 */
public class AdvertisementViewModel extends BaseViewModel<AdvertisementModel> {


    public final ObservableField<Advertisement> advertisementField = new ObservableField<>();
    public final ObservableField<Long>          timeField          = new ObservableField<>();


    public AdvertisementViewModel(@NonNull Application application, AdvertisementModel model) {

        super(application, model);


    }

    @Override
    public void onCreate() {
        super.onCreate();

        Advertisement advertisement = (Advertisement) Objects.requireNonNull(getIntent().getExtras()).getSerializable(Constants.ActivityExtra.ENTITY);

        advertisementField.set(advertisement);

        addSubscribe(Flowable.intervalRange(0, 4, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> timeField.set(3 - aLong))
                .doOnComplete(() -> skip())
                .subscribe());

    }

    @BindingAdapter({"app:imageUrl"})
    public static void setImageUrl(ImageView imageView, String url) {
        Context context = imageView.getContext();
        Glide.with(context).load(url).error(R.mipmap.splash_bg).placeholder(R.mipmap.splash_bg).into(imageView);
    }

    public void skip() {

        RouteUtil.forwardHome(getApplication().getApplicationContext());
        getUIChangeLiveData().getFinishActivityEvent().call();

    }

    public void openAdvertisement(String imgHttpUrl) {

        if (StringUtil.isEmpty(imgHttpUrl)) {

            RouteUtil.forwardHome(getApplication().getApplicationContext());

            UMengEventUtils.getInstance(getApplication().getApplicationContext()).openScreenAdvertisementEvent();
            Bundle bundle = new Bundle();
            bundle.putString(Constants.ActivityExtra.PARAM_URL, imgHttpUrl);
            //            showActivity(PublicAppBarBrowserActivity.class, bundle);

            getUIChangeLiveData().getFinishActivityEvent().call();

        }

    }

}
